<?php


namespace app\api\controller;

use app\api\model\MeetCheckModel;
use app\api\model\MeetModel;
use app\api\model\MeetNoticeModel;
use app\api\model\MeetTopicModel;
use app\api\model\MeetTypeModel;
use app\api\model\MeetUserModel;
use app\api\model\room\RoomOrderModel;
use app\api\model\room\RoomTimesModel;
use app\api\model\room\RoomWeekModel;
use app\common\controller\Api;
use think\Db;

class MeetTopic extends Api
{
// 无需登录的接口,*表示全部
    protected $noNeedLogin = ['cate'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    //参与人的议题详情列表
    public function lists3()
    {

    }

    // 审核列表
    public function lists()
    {
        $limit = input('limit') ? input('limit') : '15';
        $map = [];
        if (!empty(input('status'))) {
            $map = [
                'status' => input('status'),
            ];
        }
        $meet_id = input('meet_id');

        $model = MeetModel::get($meet_id);
        if (!$model) {
            $this->error('会议不存在');
        }
        $map['meet_id'] = input('meet_id');
        $userIds = $this->auth->id;
        $model['auth_id'] = $userIds;
        $list = MeetTopicModel::where($map)->whereNull('deletetime')
            ->order("id desc")
            ->paginate($limit)->each(function ($item, $key) use (&$model) {
                $item['user'] = MeetUserModel::where("id", "in", $item['user_id'])->field("id,nickname,username,avatar")->find();
                if($model['role_type'] == 4){
                    $check_type = 'topic'; //查询校长审核记录
                }else{
                    $check_type = 'vote'; //查询参与人表决记录
                }
                $checkList= MeetCheckModel::where("topic_id", "in", $item['id'])
                    ->where('type',$check_type)
                    ->field("id,status,user_id,content,files,createtime")
                    ->order("id desc")
                    ->select();
                foreach ( $checkList  as $k => &$val) {
                    $user = \app\common\model\User::get($val['user_id']);
                    $username = $user?$user['nickname']:'';
                    $check_status = $val['status'] == 1?'通过':'驳回';
                    $val['check_text'] = $username.$check_status;
                    $val['check_status'] = $val['status'];
                    $val['nickname'] = $username;
                    $val['status_name'] = $val['status'] == 1?"通过":"不通过";
                }
                $item['check'] = $checkList;
                $user = $this->auth->getUser();

                if($model['role_type'] == 4){
                    $map = [
                        'user_id' => $user['id'],
                        'type' =>$check_type,
                        'topic_id' => $item['id'],
                        'status' => ['<',2],
                    ];
                    $row = MeetCheckModel::where($map)
                        ->field("id")
                        ->find();
                }else{
                    $map = [
                        'user_id' => $user['id'],
                        'type' =>$check_type,
                        'topic_id' => $item['id'],
                    ];
                    $row = MeetCheckModel::where($map)
                        ->field("id")
                        ->find();
                }
                //参与人对议题今夕表决 1= 未表决 0= 已表决
                $item['is_check'] = $row?0:1;
                $action = [];
                if ($item['status'] == 2) {
                    if (in_array($model['auth_id'], explode(",", $model['check_ids']))) {
                        $action['is_pass_topic'] = 1;
                        $action['is_pass_topic_str'] = "通过";
                        $action['is_reject_topic'] = 1;
                        $action['is_reject_topic_str'] = "驳回";
                    }
                }
                if ( $model['auth_id'] ==  $model['user_id'] ) {
                    $action['is_edit_topic'] = 1;
                    $action['is_edit_topic_str'] = "修改";
                }
                $item['status_name'] = getTopicStatusName($item['status']);
                $item['action']   = $action;
                return $item;
            })->toArray();
        $this->success('成功', $list);

    }

    // 详情
    public function userdetail()
    {
        $user = $this->auth->getUser();
        $meet_id = input('meet_id');
        $map = [
            'meet_id' => $meet_id,
            'user_id' => $user['id'],
        ];
        $info = MeetTopicModel::where($map)->find();
        if(empty($info)){
            $this->success('成功',[]);
        }
        $checkList= MeetCheckModel::where("topic_id", "in", $info['id'])
            ->where('type','topic')
            ->field("status,user_id,content,files,createtime")
            ->order("id desc")
            ->select();
        $info['user'] = [
            'avatar' => $user['avatar'],
            'nickname' => $user['nickname']
        ];
        foreach ( $checkList  as $k => &$val) {
            $user = \app\common\model\User::get($val['user_id']);
            $username = $user ? $user['nickname'] : '';
            $check_status = $val['status'] == 1 ? '通过' : '驳回';
            $val['check_text'] = $username . $check_status;
            $val['check_status'] = $val['status'];
            $val['status_name'] = $val['status'] ? "同意" : "不同意";
            //$val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
            if (!empty($val['files'])) {
                $val['files'] = json_decode(str_replace('&quot;', '"', $val['files']), true);
            } else {
                $val['files'] = [];
            }
        }
        if(empty($checkList)){
            $checkList = [
                ['status' => 2,'check_text' => '待审核','content' => '','createtime_text' => date('Y-m-d H:i',$info['createtime'])]
            ];
        }
        if($info['status'] == 2 && !empty($checkList)){
            $checkList = collection($checkList)->toArray();
            array_push($checkList, ['status' => 0,'check_text' => '已提交，等待审核','content' => '','createtime_text' => date('Y-m-d H:i',$info['updatetime'])]);
        }
        $info['check_lis'] = $checkList;
        $this->success('成功', $info);
    }

    // 详情
    public function detail()
    {
        $input = input();
        $user = $this->auth->getUser();
        $input['user_id'] = $this->auth->id;
        $input['nickname'] = $user['nickname'];
        $info = MeetTopicModel::detail($input);
        $this->success('成功', $info);
    }

    public function add()
    {
        $user = $this->auth->getUser();
        $input = input();
        $meet_id = input('meet_id');
        $meet = MeetModel::get($meet_id);
        if (!$meet) {
            $this->error('会议不存在');
        }
        if (empty($input['content'])) {
            $this->error('请填写议题内容');
            return;
        }
        if(!empty($input['images'])){
            $input['images'] = htmlspecialchars_decode($input['images']);
        }
        if(!empty($input['files'])){
            $input['files'] = htmlspecialchars_decode($input['files']);
        }
        $checkRole = MeetModel::checkActionRole($meet,$this->auth->id,'attend_topic');
        if($checkRole['status'] == 0 ){
            $this->error($checkRole['msg']);
        }
        $input['status'] = 2;
        $input['nickname'] = $user['nickname'];
        $map = [
            'meet_id' => $input['meet_id'],
            'user_id' => $this->auth->id,
        ];
        $res = MeetTopicModel::where($map)->find();
        if ($res) {
            $model = new MeetTopicModel();
            $row = $model->allowField(true)->save($input,['id'=> $res['id']]);
            $input['topic_id'] = $res['id'];
            $input['user_id'] = $this->auth->id;
            $meet->is_yiti = 1;
            $meet->save();
            $info = MeetNoticeModel::sendMeetNotice($input,"topic_add",$meet);
            $this->success($info['msg'], $info);
        } else {
            $input['user_id'] = $this->auth->id;
            $model = new MeetTopicModel($input);
            $row = $model->allowField(true)->save();
            $input['topic_id'] = $model->getLastInsID();
            $info = MeetNoticeModel::sendMeetNotice($input,"topic_add",$meet);
            $meet->is_yiti = 1;
            $meet->save();
            $this->success($info['msg'], $info);
        }

        $this->success('添加成功', $row);
    }

    public function edit()
    {
        $user = $this->auth->getUser();
        $input = input();
        $id = input('id');
        $model = MeetTopicModel::get($id);
        if (!$model) {
            $this->error('会议议题不存在');
        }

        $meet_id = $model['meet_id'];
        $meet = MeetModel::get($meet_id);
        if (!$meet) {
            $this->error('会议不存在');
        } elseif ($meet['status'] == 2) {
            $this->error('该会议的会议室还未审核');
        } elseif ($meet['status'] == 9) {
            $this->error('会议已经结束');
        }
        $checkRole = MeetModel::checkActionRole($meet,$this->auth->id,'attend_topic');
        if($checkRole['status'] == 0 ){
            $this->error($checkRole['msg']);
        }

        $model = new MeetTopicModel();
        $row = $model->allowField(true)->save($input, ['id' => $input['id'], 'user_id' => $this->auth->id]);
        $this->success('修改成功', $row);
    }

    public function delete()
    {
        $input = input();
        $model = new MeetTopicModel();
        $row = $model->where(['id' => $input['id'], 'user_id' => $this->auth->id])->delete();
        if ($row) {
            $this->success('删除成功', $row);
        } else {
            $this->error('删除失败');
        }
    }

}
